package com.syscom.common.utils.generator.vue;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.syscom.common.utils.TextUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wjz
 * @date 2021/1/4 9:51
 * @Description vue文件模板生成器
 */
@Component
public class VueGenerator {

    private void textAppend(String filePath, String path, String name) {

        String content = FileUtil.readUtf8String(filePath)
                .replace("//导入点", StrUtil.format("import {} from './{}/{}'\n//导入点", name, path, name))
                .replace("//插入点", StrUtil.format("{},\n//插入点", name));
        FileUtil.writeUtf8String(content, filePath);
    }

    private void generatorVue(Configuration configuration, String templateName, Map dataModel, String outPath) throws IOException {
        Writer out = null;
        Template template = configuration.getTemplate(templateName + ".ftl");
        try {
            out = new FileWriter(FileUtil.touch(outPath));
            template.process(dataModel, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    public void generator(Map dataModel, String path, String name) throws Exception {
        // 第一步：创建一个Configuration对象，直接new一个对象。构造方法的参数就是freemarker对于的版本号。
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 第二步：设置模板文件所在的路径。
        configuration.setDirectoryForTemplateLoading(new ClassPathResource("template/vue").getFile());
        // 第三步：设置模板文件使用的字符集。一般就是utf-8.
        configuration.setDefaultEncoding("utf-8");
        String outPath = System.getProperty("user.dir") + "/WebApp/vue-general-template/src";
        Map<String, String> fileList = new HashMap() {{
            put("vueTemplate.vue", outPath + "/pages/" + path + "/" + name + ".vue");
            put("head.vue", outPath + "/pages/" + path + "/" + name + "Head.vue");
            put("model.vue", outPath + "/pages/" + path + "/" + name + "Model.vue");
            put("index.js", outPath + "/pages/" + path + "/" + "index.js");
            put("service.js", outPath + "/services/" + path + "/" + TextUtil.firstToLowerCase(name) + ".js");
            put("store.js", outPath + "/store/modules/" + path + "/" + TextUtil.firstToLowerCase(name) + ".js");
        }};
        for (String s : fileList.keySet()) {
            generatorVue(configuration, s, dataModel, fileList.get(s));
        }
        textAppend(outPath + "/store/modules/index.js", path, TextUtil.firstToLowerCase(name));
    }
}
